﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPSTrackingWebsiteManager.ClassManager;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class Orders : ClassManager.SessionManagerPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                beginDateSelected.SelectedDate = DateTime.Now.Date;
                endDateSelected.SelectedDate = DateTime.Now.Date;
                
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "ClientName";
                expression.SetSortOrder("Ascending");
                this.OrdersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = "Name";
                expression.SetSortOrder("Ascending");
                this.OrderDetailsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            OrdersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in OrdersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            clearOrderDetailsGrid();
            OrdersGrid.MasterTableView.Rebind();
        }

        protected void lbClearStockFilters_Click(object sender, EventArgs e)
        {
            OrderDetailsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in OrderDetailsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            OrderDetailsGrid.MasterTableView.Rebind();
        }

        public string getFormatDate(string date)
        {

            string day = date.Substring(0, 2);
            string month = date.Substring(3, 2);
            string year = date.Substring(6, 4);

            return year + '/' + month + '/' + day;
        }

        public bool isDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void GetAllStocksByOrderId()
        {
            OrderDetailsGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.OrderDetailProvider.GetAllByCompanyIDAndOrderID(getSessionManager().CompanyIDSelectedComboBox, getOrderIDSelected());
        }

        protected void OrdersGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            getInfoGrid();
            resizeGrid();
        }

        protected void resizeGrid(){
            OrdersGrid.Height = Unit.Parse((float.Parse(HiddenFieldHeight.Value.ToString()) /2).ToString());
            OrderDetailsGrid.Height = Unit.Parse((float.Parse(HiddenFieldHeight.Value.ToString()) /2).ToString());
        }

        protected void btnOrderSearch_Click(object sender, EventArgs e)
        {
            if(getInfoGrid())
                OrdersGrid.DataBind();
            resizeGrid();
        }

        protected void OrderDetailsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetAllStocksByOrderId();

            OrderDetailsGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
        }

        private void clearOrderDetailsGrid()
        {
            OrderDetailsGrid.DataSource = new string[] { };
            OrderDetailsGrid.DataBind();
            resizeGrid();
        }

        protected bool getInfoGrid() {
            SessionManager objSessionManager = getSessionManager();
            int companyID = -1;
            if (objSessionManager != null)
                companyID = objSessionManager.CompanyIDSelectedComboBox;

            try
            {
                if (beginDateSelected.SelectedDate != null)
                {
                    if (!isDate(beginDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de inicio seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de inicio para la consulta.");
                    return false;
                }

                if (endDateSelected.SelectedDate != null)
                {
                    if (!isDate(endDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de fin seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de fin para la consulta.");
                    return false;
                }

                if (beginDateSelected.SelectedDate.Value > endDateSelected.SelectedDate.Value)
                {
                    showWarningMessage("La fecha de inicio no puede ser mayor a la fecha de fin.");
                    return false;
                }

                OrdersGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.OrderProvider.GetAllByCompanyIDAndDates(companyID, beginDateSelected.SelectedDate.Value, endDateSelected.SelectedDate.Value);
                clearOrderDetailsGrid();
                return true;
                
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo obtener la información.");
                return false;
            }
        }

        protected int getOrderIDSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in OrdersGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["OrderId"].Text);
                }
            }
            catch { }
            return -1;
        }
        
        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Resumen de Rutas...');", true);
        }

        protected void btnOrderUpdateStatusPro_Click(object sender, EventArgs e)
        {
            updateOrderStatus("PRO");
            clearOrderDetailsGrid();
        }

        protected void btnOrderUpdateStatusFin_Click(object sender, EventArgs e)
        {
            updateOrderStatus("FIN");
            clearOrderDetailsGrid();
        }


        protected void updateOrderStatus(string statusId) {
            if (OrdersGrid.SelectedItems.Count > 0)
            {
                int companyID = getSessionManager().CompanyIDSelectedComboBox;
                int orderId;

                foreach (Telerik.Web.UI.GridDataItem selectedItem in OrdersGrid.SelectedItems)
                {
                    orderId = int.Parse(selectedItem["OrderId"].Text);

                    GPSTrackingDBV2Custom.Data.DataRepository.OrderProvider.updateStatus(companyID, orderId, statusId);

                }

                if (getInfoGrid())
                    OrdersGrid.DataBind();
                resizeGrid();

            }
            else
            {
                showInfoMessage("Debe seleccionar almenos un registro para poder ejecutar esta acción.");
            }
        }

        protected void OrdersGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllStocksByOrderId();
            OrderDetailsGrid.DataBind();
        }

        protected void OrdersGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearOrderDetailsGrid();
            }
        }
    }
}